﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HandyControl.Tools.Converter;
using NLog;
using NLog.LayoutRenderers;

namespace MultiCommunication.Models
{
    public enum TCPMode
    {
        Server,
        Client
    }
    public partial class TcpModel : ObservableObject
    {
        private readonly Logger Logger = LogManager.GetCurrentClassLogger();

        [ObservableProperty] public string ipAddress = "127.0.0.1";

        [ObservableProperty] public int port = 60001;

        [ObservableProperty] public TCPMode tcpMode;

        [ObservableProperty] public ObservableCollection<TCPMode> tcpModes = new ObservableCollection<TCPMode> { TCPMode.Server, TCPMode.Client };

        [ObservableProperty] public string tcpConnectButtonContent = "Connect";

        IPAddress iPAddress;
        TcpListener server;
        TcpClient client;
        public TcpModel()
        {
            iPAddress = IPAddress.Parse(IpAddress);
            server = new TcpListener(iPAddress, Port);
            client = new TcpClient();
        }
        bool isServerConnected ;
        bool isClientConnected ;

        [RelayCommand]
        public void Connect()
        {
            TcpConnectButtonContent = "Disconnect";
            if (TcpMode == TCPMode.Server)
            {
                if (!isServerConnected)
                {
                    TcpServerConnect();
                }
                else
                {
                    TcpServerDisconnect();
                }
            }
            else
            {
                if (!isClientConnected)
                {
                    TcpClientConnect();
                }
                else
                {
                    TcpClientDisconnect();
                }
            }
        }

        private void TcpClientDisconnect()
        {
            client.Dispose();
            isClientConnected = false;
            TcpConnectButtonContent = "Connect";
            Logger.Info("客户端断开连接");
        }

        private void TcpServerDisconnect()
        {
            server.Dispose();
            isServerConnected = false;
            TcpConnectButtonContent = "Connect";
            Logger.Info("服务器断开连接");
        }

        private async void TcpServerConnect()
        {
            isServerConnected = true;
            await Task.Run(() => 
            { 
                try
                {
                    server.Start();
                    Logger.Info($"服务器已启动:Port:{Port}");

                    TcpClient client = server.AcceptTcpClient();
                    Logger.Info("客户端已连接");

                    NetworkStream stream = client.GetStream();

                }
                catch (Exception ex)
                {
                    Logger.Error(ex.Message);
                }
            });
        }
        private async void TcpClientConnect()
        {
            isClientConnected = true;
            await Task.Run(() => 
            { 
                try
                {
                    
                    client.ConnectAsync(IpAddress, Port);
                    Logger.Info($"连接到服务器：IP:{IpAddress}，Port:{Port}");

                    NetworkStream stream = client.GetStream();
                   
                }
                catch (Exception ex) 
                {
                    Logger.Error(ex.Message);
                }
            });
        }
    }
}
